#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define    RES_LENGTH  10240 //接受字符的最大长度
char *    recv_msg(int sockfd){
    char * response;
    int  flag=0,recLenth=0;
    response=(char *)malloc(RES_LENGTH);
    memset(response,0,RES_LENGTH);
    for(flag=0;;){
        if((recLenth=recv(sockfd,response+flag,RES_LENGTH-flag,0))==-1){
            free(response);
            herror("Recv msg error!");
            return NULL;
        }else if(recLenth==0)
            break;
        else{
            flag+=recLenth;
            recLenth=0;
        }
    }
    response[flag]='\0';
    return response;
}

int main(int argc, char *argv[])
{
 int sockfd;
 int len;
 struct sockaddr_in address;
 int result;
 char *ch = "GET / HTTP/1.1\nHost: 127.0.0.1:8888\nConnection: keep-alive\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36\nDNT: 1\nAccept-Encoding: gzip, deflate, sdch\nAccept-Language: zh-CN,zh;q=0.8,ja;q=0.6\n\n\0";

 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 address.sin_family = AF_INET;
 address.sin_addr.s_addr = inet_addr("127.0.0.1");
 address.sin_port = htons(8887);
 len = sizeof(address);
 result = connect(sockfd, (struct sockaddr *)&address, len);

 if (result == -1)
 {
  perror("oops: client1");
  return 1;
 }
 int n;
n = send(sockfd,ch,strlen(ch),0);
    if (n < 0) 
         error("ERROR writing to socket");
     else{
     	printf("send request success\n");
     }
    char buf[1024<<3];
    printf("%s",recv_msg(sockfd));
    // n = my_read(sockfd,buf,1024<<3);
    // if (n < 0) 
    //      error("ERROR reading from socket");

 close(sockfd);
 return 0;
}
